package com.xz.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.entity.Category;
import com.xz.entity.category.OneCategory;
import com.xz.entity.category.TwoCategory;
import com.xz.entity.vo.CategoryData;
import com.xz.listener.CategoryExcelListener;
import com.xz.mapper.CategoryMapper;
import com.xz.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-08-08
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public void saveSubject(MultipartFile file, CategoryService categoryService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, CategoryData.class,new CategoryExcelListener(categoryService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneCategory> getAllOneTwoSubject() {
        List<OneCategory> finalList=new ArrayList<>();
        //查询所有的一级分类
        QueryWrapper<Category> oneWrapper=new QueryWrapper<>();
        oneWrapper.eq("parent_id",0);
        List<Category> oneList = this.baseMapper.selectList(oneWrapper);
        //查询所有的二级分类
        QueryWrapper<Category> twoWrapper=new QueryWrapper<>();
        twoWrapper.ne("parent_id",0);
        List<Category> twoList = this.baseMapper.selectList(twoWrapper);
        //遍历所有的一级分类
        for (Category category:oneList){
           OneCategory oneCategory=new OneCategory();
           BeanUtils.copyProperties(category,oneCategory);
           finalList.add(oneCategory);
            List<TwoCategory> twoCategoryList=new ArrayList<>();
            for (Category category2:twoList) {
                TwoCategory twoCategory=new TwoCategory();
                if(category2.getParentId().equals(category.getId())){
                    BeanUtils.copyProperties(category2,twoCategory);
                    twoCategoryList.add(twoCategory);
                }
            }
            oneCategory.setChildren(twoCategoryList);
        }
        return finalList;
    }
}
